
import mixin from '@/service/mixin';
import Pagination from '@/components/pagination';
import { keyMap } from '@/config';

export default {
    name: 'coupon-manual',
    components: {
        Pagination,
    },
    mixins: [mixin],
    data() {
        const checkPhone = (rule, value, callback) => {
            const re = /^09[0-9]{9}$/;
            if ((!value && (!this.issueDialog.form.serialNumber || this.issueDialog.form.serialNumber === '')) || (value && !re.test(value))) {
                return callback(new Error(this.$t('verify.plsInputCorrectPhoneNum'))); // 请输入正确手机号
            }
            callback();
        };
        const checkCouponTime = (rule, value, callback) => {
            if (value && value <= Date.now()) {
                return callback(new Error(this.$t('operation.deadlineMustAfterNow'))); // 优惠券到期时间必须大于当前时间
            }
            callback();
        };
        const checkCouponAmount = (rule, value, callback) => {
            if (value && value > 10000) {
                return callback(new Error(this.$t('operation.couponAmountMaxTips'))); // 优惠券面额最大为10000
            }
            callback();
        };
        return {
            keyMap,
            user: '',
            form: {
                discountCouponType: '', // 优惠券类型
                discountAmount: '',  // 面额
                appName: '', // App名称
                url: '',
                operationUser: '', // 操作员
                serialNumber: '', // 编号
                timeRange: [],
                timeType: '', // 时间类型
            },
            rules: {},
            appList: [],
            showAddDialog: false, // 显示发送优惠券弹框
            issueDialog: {
                isVisible: false,
                type: '',
                form: {
                    discountCouponType: '',
                    phone: '',
                    serialNumber: '',
                    appName: '',
                    dueTime: '',
                    ticketAmount: '',
                    remark: '',
                },
                rules: {
                    discountCouponType: [
                        { required: true, message: this.$t('verify.plsChoose'), trigger: 'change' }, // 请选择
                    ],
                    phone: [
                        { validator: checkPhone, trigger: 'blur' }
                    ],
                    ticketAmount: [
                        { required: true, message: this.$t('operation.plsInputDiscountAmount'), trigger: 'blur' }, // 请输入优惠券面额
                        { pattern: /^[1-9]\d*$/, message: this.$t('operation.plsInputCorrectDiscountAmount'), trigger: 'blur' }, // 请输入正确的优惠券面额
                        { validator: checkCouponAmount, trigger: 'blur' }, //
                    ],
                    appName: [
                        { required: true, message: this.$t('verify.plsChoose'), trigger: 'change' }, // 请选择
                    ],
                    dueTime: [
                        { required: true, message: this.$t('verify.plsChooseDate'), trigger: 'blur' }, // 请选择到期时间
                        { validator: checkCouponTime, trigger: 'blur' }
                    ],
                },
                isDisabledBtn: false,
            },
            issueResultDialog: {
                isVisible: false,
                time: '',
                success: 0,
                failed: 0,
                undo: 0,
            },
            pickerOptions: {
                disabledDate(date) {
                    const d = new Date();
                    d.setHours(0);
                    d.setMinutes(0);
                    d.setSeconds(0);
                    d.setMilliseconds(0);
                    return date.getTime() < d.getTime();
                },
                selectableRange: '23:59:59 - 23:59:59', // 只能选择23:59:59
                // start: '22:00',
                // step: '00:10',
                // end: '23:59',
            },
            uploadUrl: this.$apiConf.baseUrl + this.$apiConf.urlType.operation.importPhoneList,
            uploadHeader: {
                token: this.$storage.get('user').token,
                Authorization: 'Basic cGluamFtYW5nbzpwaW5qYW1hbmdvMDE4'
            },
            uploadLoading: false,
            uploadLoadSuccess: null,
            uploadLoadFailed: null,
            uploadLoadName: null,
        };
    },
    methods: {
        // 获取列表数据
        getTableData(page = this.page) {
            const params = this.fillParams(page);
            if (params) {
                this.$api.operation.selectSendTicketByParams(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                    }
                    this.tableMaxHeight = document.body.clientHeight - 280;
                });
            }
        },
        // 搜索列表数据
        search() {
            this.$refs.form.validate(val => {
                if (val) {
                    this.page.currentPage = 1;
                    this.getTableData();
                }
            });
        },
        // 配置查询和导出参数
        fillParams(page = this.page) {
            const { discountCouponType, discountAmount, appName, url, operationUser, serialNumber, timeRange, timeType } = this.form;
            const params = {
                discountCouponType, // 优惠券类型
                discountAmount,  // 面额
                appName, // App名称
                url,
                operationUser, // 操作员
                serialNumber, // 编号
                beginTime: '',
                stopTime: '',
                page: {
                    pageNo: page.currentPage,
                    pageSize: this.page.pageSize
                },
            };
            if (timeRange && timeRange.length) {
                if (timeType) {
                    params.beginTime = timeRange[0];
                    params.stopTime = timeRange[1];
                    params[timeType] = Date.now();
                } else {
                    this.$message.warning(this.$t('verify.plsChooseTimeType')); // 请选择时间类型
                    return false;
                }
            }
            return params;
        },
        getAppList() {
            const params = {
                appListDomain: this.$storage.get('user').domain
            };
            this.$api.systemManage.getAppListdomain(params).then(res => {
                const { status, data, error } = res;
                if ('1' === status && error === '00000000' && data instanceof Array) {
                    this.appList = data;
                }
            });
        },
        // 发放优惠券
        issueCoupon(type) {
            this.uploadLoadSuccess = '';
            this.uploadLoadFailed = '';
            this.uploadLoadName = '';
            this.issueDialog.form.serialNumber = '';
            this.issueResultDialog.success = 0;
            this.issueResultDialog.failed = 0;
            this.issueResultDialog.undo = 0;
            this.issueDialog.type = type;
            this.issueDialog.isVisible = true;
            this.$nextTick(() => {
                this.$refs['issueDialog.form'].resetFields();
            });
        },
        // 确认发放优惠券
        issueCouponSubmit() {
            this.$refs['issueDialog.form'].validate((valid) => {
                if (valid) {
                    const form = this.issueDialog.form;
                    if(form.serialNumber && (!this.uploadLoadSuccess || this.uploadLoadSuccess === 0)) {
                        this.$message.error(this.$t('common.plsImportLeastOne')); // 请至少成功导入一个用户
                        return
                    }
                    const params = {
                        // phone: form.phone,
                        userPhones: form.serialNumber,
                        appName: form.appName,
                        dueTime: form.dueTime,
                        remark: form.remark,
                        discountAmount: form.ticketAmount,
                        discountCouponType: form.discountCouponType,
                        operationUser: this.$storage.get('user').username,
                    };
                    if (form.phone) {
                        if (params.userPhones) {
                            params.userPhones.push(form.phone);
                        } else if (!params.userPhones) {
                            params.userPhones = [form.phone];
                        }
                    }
                    this.issueDialog.isDisabledBtn = true;
                    this.$api.operation.sendTicket(params).then(res => {
                        this.issueDialog.isDisabledBtn = false;
                        const { status, error, msg, data } = res;
                        if ('1' === status && '00000000' === error) {
                            this.issueResultDialog.time = data.sendTime;
                            if(params.phone && !params.userPhones) {
                                this.issueResultDialog.success = 1;
                            }
                            if(params.userPhones) {
                                this.issueResultDialog.success = data.successCount;
                                this.issueResultDialog.failed = data.failureCount;
                            }
                            this.issueCouponClose();
                            this.page.currentPage = 1;
                            this.getTableData();
                            this.issueResultDialog.isVisible = true;
                        }
                        else {
                            this.$message.error(msg);
                        }
                    });
                }
            })
        },
        // 关闭发放优惠券
        issueCouponClose() {
            this.uploadLoadSuccess = '';
            this.uploadLoadFailed = '';
            this.issueDialog.form.serialNumber = '';
            this.$refs['issueDialog.form'].resetFields();
            this.issueDialog.isDisabledBtn = false;
            this.issueDialog.isVisible = false;
        },
        // 上传成功
        uploadSuccess(res,file) {
            const { status, data, msg } = res;
            this.closeLoading();
            if (status === '1') {
                this.uploadLoadSuccess = data.successCount;
                this.uploadLoadFailed = data.failureCount;
                this.uploadLoadName = file.name;
                this.issueDialog.form.serialNumber = data.phones;
                this.$message.success(this.$t('common.importSuccess')); // '导入成功'
            } else {
                this.$message.error(msg || this.$t('common.importFail')); // '导入失败'
            }
            // 上传完成后重新校验手机号字段
            const form = this.$refs['issueDialog.form'];
            form.validateField('phone');
        },
        // 上传前
        beforeUpload(file) {
            let flag = false;
            const arr = file.name.split('.');
            const ext = arr[arr.length - 1];
            if (ext && (ext === 'xls' || ext === 'xlsx' || ext === 'csv')) {
                flag = true;
            }
            if (flag) {
                this.uploadLoading = true;
            } else {
                this.$message.warning(this.$t('verify.onlyExcelFile')); // 只能上传Excel文件
            }
            return flag;
        },
        // 取消上传中状态
        closeLoading() {
            this.uploadLoading = false;
        },
        // 下载手机号导入模版
        downloadMobileExcel() {
            window.location.href = '/phone.xls'
        },
        // 变更手机号
        changePhone(val) {
            if(val && !this.issueDialog.form.serialNumber) {
                this.uploadLoadSuccess = 1;
            }
        },
        // 下载该批次的手机号
        downloadPhoneList(row) {
            let url = this.$apiConf.baseUrl + this.$apiConf.urlType.operation.exportSendTicketPhone;
            url = url + '?serialNumber=' + row.serialNumber;
            url = url + '&token=' + this.user.token;
            this.$openNewBlank(url);
        },
        // 时间类型值改变
        handleTimeTypeChange(value) {
            if (!value) {
                this.form.timeRange = [];
            }
        },
    },
    filters: {
    },
    created() {
        this.user = this.$storage.get('user');
        this.getTableData({currentPage: this.page.currentPage}, this.form);
        this.getAppList();
    },
}
